package com.tron.dobest.dynamicdatasource;

import com.zaxxer.hikari.HikariDataSource;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Data
@Configuration
@EnableConfigurationProperties(value = {DynamicDataSourceProperties.class})
public class DynamicDataSourceConfig {

    @Autowired
    DynamicDataSourceProperties dynamicDataSourceProperties;


    @Bean
    @Conditional(MyDataSourceCondition.class)
    public SwitchOverDataSource switchOverDataSource() {
        return new SwitchOverDataSource();
    }

    @Bean
    public DataSource firstDataSource() {
        DataSourceProperties dataSourceProperties = dynamicDataSourceProperties.getDynamicDataSource().get(0);
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        hikariDataSource.setJdbcUrl(dataSourceProperties.getUrl());
        hikariDataSource.setUsername(dataSourceProperties.getUsername());
        hikariDataSource.setPassword(dataSourceProperties.getPassword());
        return hikariDataSource;
    }

    @Bean
    public DataSource secondDataSource() {
        DataSourceProperties dataSourceProperties = dynamicDataSourceProperties.getDynamicDataSource().get(1);
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        hikariDataSource.setJdbcUrl(dataSourceProperties.getUrl());
        hikariDataSource.setUsername(dataSourceProperties.getUsername());
        hikariDataSource.setPassword(dataSourceProperties.getPassword());
        return hikariDataSource;
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource() {
        //数据源映射关系
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("first", firstDataSource());
        targetDataSources.put("second", secondDataSource());
        //参数一：指定一个默认的数据源；参数二：所有数据源的映射关系
        return new DynamicDataSource(firstDataSource(),targetDataSources);
    }


    @Bean(name = "transactionManager")
    public DataSourceTransactionManager TransactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
